package com.example.choupaiapp.main.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.main.constant.Config;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ASUS on 2019/11/1.
 */

public class WeiboLoginUtil {

    public static SsoHandler mSsoHandler;
    private static WeiboLoginUtil qqLoginUtil = null;

    private WeiboLoginUtil() {
        WbSdk.install(ContextUtil.getContext(), new AuthInfo(ContextUtil.getContext(), Config.SINA_APP_KEY, Config.REDIRECT_URL,
                ""));
    }

    public static WeiboLoginUtil getInstance() {
        if (qqLoginUtil == null) {
            qqLoginUtil = new WeiboLoginUtil();
        }
        return qqLoginUtil;
    }

    public void weiboLogin(Activity activity, WbAuthListener listener) {
        mSsoHandler = new SsoHandler(activity);
        mSsoHandler.authorize(listener);
    }

    public boolean isWeiboAppInstalled() {
        if (WbSdk.isWbInstall(ContextUtil.getContext())) {
            return true;
        } else {
            isAvilible(ContextUtil.getContext(), "com.sina.weibo");
        }

        return false;
    }

    public boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

}
